package com.imut.oa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imut.oa.common.PageResult;
import com.imut.oa.mapper.EmployeeMapper;
import com.imut.oa.mapper.TaskMapper;
import com.imut.oa.pojo.dto.TaskDTO;
import com.imut.oa.pojo.dto.TaskPageQueryDTO;
import com.imut.oa.pojo.entity.Departments;
import com.imut.oa.pojo.entity.Leave;
import com.imut.oa.pojo.entity.Task;
import com.imut.oa.pojo.entity.User;
import com.imut.oa.pojo.vo.LeaveVO;
import com.imut.oa.pojo.vo.TaskVO;
import com.imut.oa.service.EmployeeService;
import com.imut.oa.service.TaskService;
import com.imut.oa.util.ThreadLoaclUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task>
        implements TaskService {
    @Autowired
    private TaskMapper taskMapper;
    @Override
    public PageResult getTaskPage(TaskPageQueryDTO taskPageQueryDTO) {
        // 创建条件对象，不设置任何条件，相当于查询所有
        Page<TaskVO> page = new Page<>(taskPageQueryDTO.getPage(), taskPageQueryDTO.getPageSize());
        // 调用自定义的联表分页查询
        Page<TaskVO> voPage = taskMapper.selectTaskPage(page, taskPageQueryDTO);
        System.out.println(voPage);
        return new PageResult(voPage.getTotal(), voPage.getRecords());
    }

    @Override
    public void addTask(TaskDTO taskDTO) {
        Long currentId = ThreadLoaclUtil.getCurrentId();

        Task task = Task.builder()
                .assignor(currentId)
                .taskName(taskDTO.getTaskName())
                .assignee(taskDTO.getAssignee())
                .description(taskDTO.getDescription())
                .status(0)
                .isDelete(0)
                .build();
        taskMapper.insertTask(task);
    }

    @Override
    public int deleteById(Long id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public void cancelTask(Long taskId) {
        Task task = new Task();
        task.setId(taskId);
        task.setStatus(3); // 3 表示已撤销
        taskMapper.updateTask(task);
    }

    @Override
    public List<Task> getTaskHistory(int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        Long currentId = ThreadLoaclUtil.getCurrentId();
        return taskMapper.getTaskHistory(offset, pageSize,currentId);
    }

    @Override
    public void acceptTask(Long taskId) {
        Task task = new Task();
        task.setId(taskId);
        task.setStatus(1);
        taskMapper.updateTask(task);
    }

    @Override
    public void completeTask(Long taskId) {
        Task task = new Task();
        task.setId(taskId);
        task.setStatus(2);
        taskMapper.updateTask(task);
    }
}
